<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="846px"
      :title="model.text"
      wrapClassName="add-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body" v-loading="formLoading">
        <a-row :gutter="0">
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :hideRequiredMark="model.text == '查看' ? true : false"
          >
            <a-col :span="12">
              <!-- 组织编码   （编辑页面时此字段不可编辑） -->
              <a-form-model-item ref="orgCode" label="组织编码" prop="orgCode">
                <a-input
                  v-model.trim="form.orgCode"
                  :disabled="model.id ? true : false"
                  placeholder="请输入组织编码"
                  :maxLength="100"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <!-- 组织名称 -->
              <a-form-model-item ref="orgName" label="组织名称" prop="orgName">
                <a-input
                  v-model.trim="form.orgName"
                  placeholder="请输入组织名称"
                  :disabled="model.text == '查看' ? true : false"
                  :maxLength="255"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <!-- 组织单位名称 -->
              <a-form-model-item
                ref="orgNuitName"
                label="组织单位名称"
                prop="orgNuitName"
              >
                <a-input
                  v-model.trim="form.orgNuitName"
                  placeholder="请输入组织单位名称"
                  :disabled="model.text == '查看' ? true : false"
                  :maxLength="255"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <!-- 排序 -->
              <a-form-model-item ref="sort" label="排序" prop="sort">
                <a-input
                  type="number"
                  :maxLength="10"
                  v-model="form.sort"
                  placeholder="请输入排序"
                  :disabled="model.text == '查看' ? true : false"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <!-- 所属租户 -->
              <a-form-model-item
                ref="tenantCode"
                label="所属租户"
                prop="tenantCode"
              >
                <a-input
                  v-if="model.text == '查看'"
                  v-model="tenantName"
                  disabled
                />
                <a-tree-select
                  v-else
                  placeholder="请选择所属租户"
                  :replaceFields="{
                    children: 'child',
                    title: 'tenantName',
                    key: 'id',
                    value: 'tenantCode',
                  }"
                  v-model="form.tenantCode"
                  :tree-data="tenantSource"
                  @change="tenantChange"
                  style="max-width: 253px"
                >
                </a-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <!-- 组织类型 -->
              <a-form-model-item
                ref="orgTypeValue"
                label="组织类型"
                prop="orgTypeValue"
              >
                <a-select
                  v-model="form.orgTypeValue"
                  placeholder="请选择组织类型"
                  :loading="organizationTypeLoading"
                  @change="orgChange"
                  :disabled="model.text == '查看' ? true : false"
                >
                  <a-select-option
                    :value="item.dicValue"
                    v-for="(item, index) in organizationTypeSource"
                    :key="index"
                  >
                    {{ item.dicDesc }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <!-- 角色 -->
              <a-form-model-item ref="roleIds" label="角色" prop="roleIds">
                <a-input
                  v-if="model.text == '查看'"
                  v-model="roleNames"
                  disabled
                />
                <!-- :getPopupContainer="selectContainer" -->
                <a-select
                  v-else
                  v-model="form.roleIds"
                  mode="multiple"
                  :maxTagCount="1"
                  placeholder="请选择角色"
                  :loading="roleLoading"
                  style="max-width: 253px"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="(item, index) in roleSource"
                    :key="index"
                  >
                    {{ item.roleName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="form.orgTypeValue == 5">
              <!-- 标段类型 -->
              <a-form-model-item
                ref="secTypeValue"
                label="标段类型"
                prop="secTypeValue"
              >
                <a-select
                  v-model="form.secTypeValue"
                  placeholder="请选择标段类型"
                  :loading="secTypeLoading"
                  :disabled="model.text == '查看' ? true : false"
                >
                  <a-select-option
                    :value="item.dicValue"
                    v-for="(item, index) in secTypeSource"
                    :key="index"
                  >
                    {{ item.dicDesc }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="form.orgTypeValue == 5">
              <!-- 路线坐标 -->
              <a-form-model-item
                ref="routeCoordinates"
                label="路线坐标"
                prop="routeCoordinates"
              >
                <a-input
                  v-model="form.routeCoordinates"
                  disabled
                  placeholder="请绘制线路坐标"
                  type="textarea"
                  style="height: 100px"
                />
                <div class="map-container">
                  <div id="organization-map"></div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
      </div>
      <div class="curve-modal-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button
          type="primary"
          v-if="model.text != '查看'"
          :loading="loading"
          @click="submit()"
        >
          提交
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
//【新增子节点】
import { getUserRole } from "@/api/user-center/userManage.js";
import { notificationTip, getProInitGeo, addAttributeByKey } from "@/utils";
import { getLoginData } from "@/tools";
import {
  getNewTenantList,
  getNewDictList,
  getDictList,
  getOrganizationAdd,
  getOrganizationDetails,
} from "@/api/user-center/organizationManage.js";
let mapInstance = null;
export default {
  name: "addChildrenNodeModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    model: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getTenantList();
          this.getOrganizationTypeList();
          if (this.model.id) {
            //所属租户
            this.form.tenantCode = this.model.tenantCode;
            this.getSecTypeList();
            this.getRoleList();
            this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      loading: false,
      form: {
        //组织编码
        orgCode: "",
        //组织名称
        orgName: "",
        //组织单位名称
        orgNuitName: "",
        //排序
        sort: "",
        //所属租户
        tenantCode: undefined,
        //组织类型
        orgTypeValue: undefined,
        //标段类型
        secTypeValue: undefined,
        //角色
        roleIds: undefined,
        //线路坐标
        routeCoordinates: "",
      },
      formLoading: false,
      rules: {
        orgCode: [
          { required: true, message: "请输入组织编码", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: "只能输入英文字母，数字，下划线，中划线",
          },
        ],
        orgName: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
        ],
        orgNuitName: [
          { required: true, message: "请输入组织单位名称", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        tenantCode: [
          { required: true, message: "请选择所属租户", trigger: "change" },
        ],
        orgTypeValue: [
          { required: true, message: "请选择组织类型", trigger: "change" },
        ],
        secTypeValue: [
          { required: true, message: "请选择标段类型", trigger: "change" },
        ],
        roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
        routeCoordinates: [{ required: true, message: "请绘制线路坐标" }],
      },
      //租户
      tenantSource: [],
      tenantLoading: false,
      //角色
      roleSource: [],
      roleLoading: false,
      //组织类型
      organizationTypeSource: [],
      organizationTypeLoading: false,
      //标段类型
      secTypeSource: [],
      secTypeLoading: false,
      roleNames: "",
      tenantName: "",
    };
  },
  mounted() {},
  methods: {
    selectContainer(triggerNode) {
      return triggerNode.parentNode;
    },
    //提交
    submit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let { form } = this;
          let { parentOrgCode } = this.model;
          let { id } = this.model;
          let formJson = {
            //组织编码
            orgCode: form.orgCode,
            //组织名称
            orgName: form.orgName,
            //组织单位名称
            orgNuitName: form.orgNuitName,
            //排序
            sort: form.sort,
            //所属租户
            tenantCode: form.tenantCode,
            //组织类型
            orgTypeValue: form.orgTypeValue,
            //标段类型
            secTypeValue: form.secTypeValue ? form.secTypeValue : "",
            //角色
            roleIds: form.roleIds.toString(),
            //线路坐标
            routeCoordinates: form.routeCoordinates,
            //父级code
            parentOrgCode,
          };
          if (id) {
            formJson.id = id;
          }
          getOrganizationAdd(formJson)
            .then((res) => {
              let msg = "新增组织子节点成功！";
              if (id) {
                msg = "编辑组织子节点成功！";
              }
              notificationTip("success", msg);
              this.closeModal();
              this.$parent.getTableData();
            })
            .catch((_) => {})
            .finally((_) => {
              this.loading = false;
            });
        }
      });
    },
    //查询详情
    getDetail() {
      this.formLoading = true;
      let { id } = this.model;
      getOrganizationDetails(id)
        .then((res) => {
          let {
            data: { result },
          } = res;
          this.roleNames = result.roleNames;
          this.tenantName = result.tenantDesc;
          this.form = {
            //组织编码
            orgCode: result.orgCode,
            //组织名称
            orgName: result.orgName,
            //组织单位名称
            orgNuitName: result.orgNuitName,
            //排序
            sort: result.sort,
            //所属租户
            tenantCode: result.tenantCode,
            //组织类型
            orgTypeValue: Number(result.orgTypeValue),
            //标段类型
            secTypeValue: result.secTypeValue
              ? Number(result.secTypeValue)
              : undefined,
            //角色
            roleIds: result.roleIds ? result.roleIds.split(",") : undefined,
            //线路坐标
            routeCoordinates: result?.routeCoordinates || "",
          };
          if (result.orgTypeValue == 5) {
            let lineData = [];
            if (this.form.routeCoordinates) {
              lineData = JSON.parse(this.form.routeCoordinates);
            } else {
              lineData = [];
            }
            this.$nextTick(() => {
              this.getInitMap(lineData);
            });
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.formLoading = false;
        });
    },
    //查询租户下拉框
    getTenantList() {
      this.tenantLoading = true;
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getNewTenantList({ userId })
          .then((res) => {
            let { data } = res;
            let tree = data?.result || [];
            this.tenantSource = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              tree,
              "child"
            );
            resolve();
          })
          .catch((_) => {
            this.tenantSource = [];
            reject();
          })
          .finally((_) => {
            this.tenantLoading = false;
          });
      });
    },
    //选择租户
    tenantChange() {
      this.form.roleIds = undefined;
      this.getRoleList();
    },
    //查询角色下拉框
    getRoleList() {
      this.roleLoading = true;
      let { tenantCode } = this.form;
      getUserRole({ tenantCode })
        .then((res) => {
          let { data } = res;
          this.roleSource = data.result || [];
        })
        .catch((_) => {
          this.roleSource = [];
        })
        .finally((_) => {
          this.roleLoading = false;
        });
    },
    //查询组织类型下拉框
    getOrganizationTypeList() {
      this.organizationTypeLoading = true;
      getNewDictList({ dictKey: "orgType" })
        .then((res) => {
          let { data } = res;
          this.organizationTypeSource = data.result || [];
        })
        .catch((_) => {
          this.organizationTypeSource = [];
        })
        .finally((_) => {
          this.organizationTypeLoading = false;
        });
    },
    //选择组织
    orgChange() {
      this.form.secTypeValue = undefined;
      this.form.routeCoordinates = "";
      if (this.form.orgTypeValue == 5) {
        this.getSecTypeList();
        this.$nextTick(() => {
          this.getInitMap();
        });
      }
    },
    //查询标段类型
    getSecTypeList() {
      this.secTypeLoading = true;
      getDictList({ dictKey: "secType" })
        .then((res) => {
          let { data } = res;
          this.secTypeSource = data.result || [];
        })
        .catch((_) => {
          this.secTypeSource = [];
        })
        .finally((_) => {
          this.secTypeLoading = false;
        });
    },
    //地图加载
    getInitMap(eletricFenceData = []) {
      //地图中心点
      let center = Math.ceil(eletricFenceData.length / 2);
      mapInstance = new AMap.Map("organization-map", {
        zoom: 15,
        center: [
          eletricFenceData?.[center]?.[0] || getProInitGeo()[0],
          eletricFenceData?.[center]?.[1] || getProInitGeo()[1],
        ],
      });
      if (!this.model.id || eletricFenceData.length == 0) {
        this.drawLine();
        return;
      } else {
        this.editLine(eletricFenceData);
      }
    },
    //绘制折线
    drawLine() {
      let _this = this;
      AMap.plugin(["AMap.MouseTool"], async function (e) {
        var mouseTool = new AMap.MouseTool(mapInstance);
        mouseTool.polyline({
          fillColor: "#ff15ff",
          strokeOpacity: 1,
          fillOpacity: 0.2,
          strokeColor: "#ff15ff",
          strokeWeight: 2,
          strokeStyle: "solid",
          strokeDasharray: [5, 5],
        });
        AMap.Event.addListener(mouseTool, "draw", function (pt) {
          //添加事件
          var arr = pt.obj.getPath();
          let pathArr = [];
          for (var i = 0; i < arr.length; i++) {
            pathArr.push([arr[i].lng, arr[i].lat]);
          }
          _this.form.routeCoordinates = JSON.stringify(pathArr);
        });
      });
    },
    //编辑折线
    editLine(path = []) {
      let _this = this;
      var polyline1 = new AMap.Polyline({
        path: path,
        fillColor: "#ff15ff",
        strokeOpacity: 1,
        fillOpacity: 0.2,
        strokeColor: "#ff15ff",
        strokeWeight: 2,
        strokeStyle: "solid",
        strokeDasharray: [5, 5],
      });
      mapInstance.add(polyline1);
      mapInstance.setFitView();
      if (this.model.text == "编辑子节点") {
        AMap.plugin(["AMap.PolylineEditor"], async function (e) {
          let polyEditor = new AMap.PolylineEditor(mapInstance, polyline1, {
            //编辑样式
            editOptions: {
              strokeColor: "#ff15ff",
              strokeWeight: 2,
              fillColor: "#ff15ff",
              fillOpacity: 0.2,
            },
          });
          polyEditor.close();
          polyEditor.setTarget(polyline1);
          polyEditor.open();
          polyEditor.on("adjust", (ev) => {
            _this.getAllSpot(polyEditor);
          });
          polyEditor.on("addnode", (ev) => {
            _this.getAllSpot(polyEditor);
          });
          polyEditor.on("removenode", (ev) => {
            _this.getAllSpot(polyEditor);
          });
        });
      }
    },
    //获取地图上所有标点
    getAllSpot(e) {
      var arr = e.getTarget().getPath();
      let pathArr = [];
      for (var i = 0; i < arr.length; i++) {
        pathArr.push([arr[i].lng, arr[i].lat]);
      }
      this.form.routeCoordinates = JSON.stringify(pathArr);
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    //重置表单
    resetForm() {
      this.form = {
        //组织编码
        orgCode: "",
        //组织名称
        orgName: "",
        //组织单位名称
        orgNuitName: "",
        //排序
        sort: "",
        //所属租户
        tenantCode: undefined,
        //组织类型
        orgTypeValue: undefined,
        //标段类型
        secTypeValue: undefined,
        //角色
        roleIds: undefined,
        //线路坐标
        routeCoordinates: "",
      };
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0;
  }
  .curve-modal-body {
    padding: 20px 60px 20px 40px;
    max-height: 620px;
    .custom-scrollbar();
  }
  .curve-modal-footer {
    text-align: center;
    padding-bottom: 20px;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .ant-form-item {
    .flex();
    .ant-form-item-label {
      flex-shrink: 0;
      width: 120px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
  .map-container {
    width: 100%;
    height: 340px;
    position: relative;
    .box-sizing();
    border: 2px solid #fff;
    border-radius: 4px;
    #organization-map {
      height: 100%;
      width: 100%;
    }
  }
}
</style>
